<?php

namespace DreamCat\FrameCore;

use DreamCat\FrameCore\Factory\Impl\Container\DefaultContainerFactory;
use DreamCat\FrameInterface\ConfigReader;
use DreamCat\FrameInterface\Factory\ContainerFactory;
use DreamCat\FrameInterface\HttpHandle\HttpRequestProcess;

/**
 * FPM入口
 * @author vijay
 */
class FpmEntrance
{
    /**
     * 启动入口函数
     * @param string $rootDir 项目根目录，传null则使用当前工作目录
     * @param ContainerFactory $containerFactory 容器工厂，不传入则使用默认
     * @return void
     */
    public static function start(string $rootDir = null, ContainerFactory $containerFactory = null): void
    {
        $rootDir = $rootDir === null ? getcwd() : realpath($rootDir);
        if ($containerFactory === null) {
            $containerFactory = new DefaultContainerFactory();
        }
        (new FpmEntrance())->run(new ConfigReaderImpl($rootDir), $containerFactory);
    }

    /**
     * 启动入口函数
     * @param ConfigReader $configReader 配置读取器
     * @param ContainerFactory $containerFactory 容器工厂，不传则使用默认
     * @return void
     */
    public static function startWithConfigReader(
        ConfigReader $configReader,
        ContainerFactory $containerFactory = null
    ): void {
        if ($containerFactory === null) {
            $containerFactory = new DefaultContainerFactory();
        }
        (new FpmEntrance())->run($configReader, $containerFactory);
    }

    /**
     * 入口函数
     * @param ConfigReader $configReader
     * @param ContainerFactory $containerFactory
     * @return void
     */
    protected function run(ConfigReader $configReader, ContainerFactory $containerFactory): void
    {
        $container = $containerFactory->create($configReader);
        /** @var HttpRequestProcess $handle */
        $handle = $container->get(HttpRequestProcess::class);
        $handle->handle($container);
    }
}

# end of file
